package com.huike.business.service.impl;


import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.common.core.domain.entity.SysDictData;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商机跟进记录Service业务层处理
 *
 * @author wgl
 * @date 2021-04-28
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {
    @Autowired
    private TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private TbBusinessMapper tbBusinessMapper;

    /**
     * 查询商机跟进记录
     */
    @Override
    public List<TbBusinessTrackRecord> findList(Long id) {
        //校验参数
        if (id == null) return null;
        //查询跟进记录
        List<TbBusinessTrackRecord> list = tbBusinessTrackRecordMapper.selectRecordByBusinessId(id);

        List<TbBusinessTrackRecord> collect = list.stream().peek(c -> {
            String[] strings = c.getKeyItems().split(",");
            for (String string : strings) {
                SysDictData sysDictData = sysDictDataMapper.selectDictDataById(Long.valueOf(string));
                c.getKeys().add(sysDictData.getDictLabel());
            }
        }).collect(Collectors.toList());
        //查询字典
        return collect;
    }

    /**
     * 添加商机根跟进记录
     */
    @Override
    @Transactional
    public boolean add(BusinessTrackVo businessTrackVo) {
        //校验参数
        if (businessTrackVo == null) return false;
        //添加跟进记录
        String username = SecurityUtils.getUsername();
        Date date = DateUtils.getNowDate();
        int i = tbBusinessTrackRecordMapper.insert(businessTrackVo, username, date);
        //填充客户基本信息
        //创建商机对象
        TbBusiness tbBusiness = new TbBusiness();
        //复制属性
        BeanUtils.copyProperties(businessTrackVo, tbBusiness);
        tbBusiness.setId(businessTrackVo.getBusinessId());
        int j = tbBusinessMapper.updateTbBusiness(tbBusiness);
        return i > 0 && j > 0;
    }
}
